<template>
  <div class="myFollow" style="padding-top: 10px">
    <el-table :data="tableData" border style="width: 100%; padding: 20px">
      <el-table-column prop="name" label="课程名称"></el-table-column>
      <el-table-column prop="teacher" label="课程老师"></el-table-column>
      <el-table-column
        prop="peopleNumber"
        label="参与学生人数"
      ></el-table-column>
      <el-table-column prop="info" label="课程简介"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="clickAnd(scope.row, scope.$index)"
            >{{ scope.row.type }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { courses, schools } from "../../../public/schoolData.js";
export default {
  data() {
    return {
      tableData: courses,
      type: "",
      studentId: JSON.parse(sessionStorage.getItem("studentInfo")).studentId,
    };
  },
  created() {
    this.inCourseList = schools.find((data) => {
      return data.id == this.studentId;
    }).inCourseList;
    this.tableData = this.tableData.map((element) => {
      if (this.inCourseList.length > 0) {
        let queryResult = this.inCourseList.some((data) => {
          return element.id == data.id;
        });
        if (queryResult) {
          element["type"] = "取消学习";
        } else {
          element["type"] = "开始学习";
        }
      } else {
        element["type"] = "开始学习";
      }
      return element;
    });
  },
  methods: {
    clickAnd(row, index) {
      if (row.type == "开始学习") {
        let num = row.peopleNumber + 1;
        courses.find((data) => {
          return data.id == row.id;
        }).peopleNumber = num;
        schools
          .find((data) => {
            return data.id == this.studentId;
          })
          .inCourseList.push({
            id: row.id,
            name: row.name,
            teacher: row.teacher, //参与的老师
            teacherId: row.teacherId, //参与的老师ID
            peopleNumber: num, //参与人数
            info: row.info, //课程的内容
          });
        row.type = "取消学习";
      } else {
        let num = row.peopleNumber - 1;
        courses.find((data) => {
          return data.id == row.id;
        }).peopleNumber = num;
        let indexDel = courses[index];
        schools
          .find((data) => {
            return data.id == this.studentId;
          })
          .inCourseList.splice(indexDel, 1);
        console.log(indexDel);
        row.type = "开始学习";
      }
    },
  },
};
</script>

<style>
</style>